﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Xml;

namespace publicLibrary
{
    public static class staticClass
    {

        public static string tranBoolValue(this bool? it, string a = "是", string b = "否", string c = "未知")
        {
            if (it == null) { return c; } else { if (it == true) { return a; } else { return b; } }


        }
        public static T getListDefaultItem<T>(this IList<T> obj, T defaultItem)
        {
            if (obj == null || obj.Count == 0) return defaultItem;
            return obj.FirstOrDefault();
        }

        public static HtmlString ListToHTMLbyCode(this List<string> obj,string htmlCode,int ii=0) 
        { 
            string html="";
            if (obj == null) return new HtmlString(html);
            foreach (var i in obj) {
               html += htmlCode.Replace("_var_", i);
               if (--ii == 0) { break; }
            }
            return new HtmlString(html);    
        }
        /// <summary>
        /// 用","分割字符串，并把分割后的结果替换htmlCode中的"_var_"，生成一串html
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="htmlCode"></param>
        /// <returns></returns>
        public static HtmlString SplitToHTMLbyCode(this string obj, string htmlCode)
        {
            string html = "";
            if (obj == null) return new HtmlString(html);
            String[] _obj = obj.Split(',');
            for (var i=0;i<_obj.Length;i++)
            {
                if (!string.IsNullOrWhiteSpace(_obj[i]))
                {
                    html += htmlCode.Replace("_var_", _obj[i]);
                }
            }
            return new HtmlString(html);
        }
        /// <summary>
        /// 用","分割字符串，并把分割后的结果替换htmlCode中的"_var_"，生成一串html
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="htmlCode"></param>
        /// <returns></returns>
        public static HtmlString SplitToHTMLbyCode(this List<string> obj, string htmlCode)
        {
            string html = "";
            if (obj == null) return new HtmlString(html);
            String[] _obj = obj.ToArray();
            for (var i = 0; i < _obj.Length; i++)
            {
                if (!string.IsNullOrWhiteSpace(_obj[i]))
                {
                    html += htmlCode.Replace("_var_", _obj[i]);
                }
            }
            return new HtmlString(html);
        }
        /// <summary>
        /// htmlCode中_varA_,varB_;对应string，string
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="htmlCode"></param>
        /// <returns></returns>
        public static HtmlString SplitToHTMLbyCode(this Dictionary<string,string> obj, string htmlCode)
        {

            string html = "";
            if (obj == null) return new HtmlString(html);
            
            foreach (var i in obj)
            {
                html += htmlCode.Replace("_varA_", i.Key).Replace("_varB_",i.Value);
            }
            return new HtmlString(html);
        }
        /// <summary>
        /// 针对dict的cache，通过给出keys的字符串("01,02,03")，在dict中找到对应values并替换返回，，********有问题，是否反回来string,Dictionary
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string tansValue(this Dictionary<string, string> obj, string str,string undef="没找到") {
            if(string.IsNullOrWhiteSpace(str)){return "无";}
            string[] strs = str.Split(',');
            for (var i = 0; i < strs.Length;i++ )
            {
                try
                {
                    strs[i] = obj[strs[i]];
                }
                catch (Exception e)
                {
                    strs[i] = undef;
                }
            }
            return string.Join(",", strs);
            
        }
        public static string ToJSON(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static string ToJSON(this object obj, int recusionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recusionDepth;
            return serializer.Serialize(obj);
        }

        public static int? ToInt(this object obj)
        {
            if (obj == null) return null;

            try
            {
                return Convert.ToInt32(obj);
            }
            catch
            {
                return null;
            }
        }

        public static DateTime? ToDateTime(this object obj)
        {
            try
            {
                return Convert.ToDateTime(obj);
            }
            catch
            {
                return null;
            }
        }
        public static string[] tryToArray(this IEnumerable<string> ls)
        {
            if (ls != null)
            {
                return ls.ToArray<string>();
            }
            return null;

        }
        public static string tryJoin(this IEnumerable<string> ls, string splitStr)
        {
            if (ls != null)
            {
                return String.Join(splitStr, ls);
            }
            return "";

        }
        public static int? tryToInt(this string str)
        {
            try
            {
                return Convert.ToInt32(str);
            }
            catch
            {
                return null;
            }
        }
        public static string ToTryString(this object obj)
        {
            return obj == null ? null : obj.ToString();
        }

        public static string tryValue(this Dictionary<string, string> Dictionary,string key,string tryVal="")
        {
            try
            {
                return Dictionary[key];
            }
            catch
            {
                return tryVal;
            }
        }

        public static string[] trySplit(this string str, string separator=",")
        {
            //separator = separator ?? System.Environment.NewLine;
            //separator = separator ?? ",";
            if (string.IsNullOrWhiteSpace(str)) return new string[]{null};
            return str.Split(new string[] { separator },System.StringSplitOptions.RemoveEmptyEntries);
        }
        
        public static string ajax(ActionResult w) {
            return "";
        }

        public static string md5(this string str)
        {
            //return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
            return str;
        }

        /// <summary>
        /// 计算平局值，如果value为空。返回""
        /// </summary>
        /// <param name="value">值</param>
        /// <param name="number">数</param>
        /// <param name="type">小数类型</param>
        /// <returns></returns>
        public static HtmlString sumValue(double value)
        {
            if (value == 0) {
                return new HtmlString("<span class='gray'>暂无评分</span>");
            }

            return new HtmlString(value.ToString("0.0"));

        }
        public static HtmlString toSumValue(this double value, string str = "暂无评分")
        {
            if (value == 0)
            {
                return new HtmlString("<span class='gray'>"+str+@"</span>");
            }

            return new HtmlString(value.ToString("0.0"));

        }
        /// <summary>
        /// 
        /// </summary>
        public static List<Dictionary<string, string>> JsonStrToDict(this String str)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Deserialize<List<Dictionary<string, string>>>(str);
            

            
        }
        /// <summary>
        /// 更新this中item记录
        /// this为自定制的类型对象的特定json字段所服务
        /// _item 为Dictionary的Json对象
        /// 操作依据的Json字段名
        /// </summary>
        /// <param name="dict"></param>
        /// <param name="_item"></param>
        /// <param name="Field"></param>
        public static List<Dictionary<string, string>> updateJsonDict(this List<Dictionary<string, string>> dict, Dictionary<string, string> _item, string Field)
        {
            int index = dict.FindIndex(d => d[Field] == _item[Field]);
            if (index < 0)
            {
                //不存name记录时增加新的
                dict.Add(_item);
            }
            else {
                //修改
                 dict[index] = _item;
            }
            return dict;
           
        }
        public static void UpdateJsonStr(this String obj,string filed, string oldVal,string newVal)
        {        /// {id:菜ID,name:菜名,count:推荐数,date:最后推荐时间},{id:菜ID,name:菜名,count:推荐数,date:创建时间},
            /*string _str = filed + ":" + oldVal;
            if (obj.IndexOf(_str) > 0)
            {
                obj.Replace(_str, filed + ":" + newVal);
            }
            else { 
            
            }*/

        }
        /// <summary>
        /// object 的json序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string getJson(this Object obj)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(obj);
        }
    }
    /// <summary>
    /// 准备把shop中item和其它用到jsonStr的字段 采用myJsonStr类，和大非商量*****
    /// jsonList的类型对象为特定json字段所服务
    /// </summary>
    public class MyJsonStr
    {
        public string Jsonstr;
        public List<Dictionary<string, string>> jsonList;
        
        public MyJsonStr(string str)
        {
            if (str == null)
            {
                this.Jsonstr = "";
                this.jsonList = new List<Dictionary<string, string>>();
            }
            else
            {
                this.Jsonstr = str;
                JavaScriptSerializer jss = new JavaScriptSerializer();
                this.jsonList = jss.Deserialize<List<Dictionary<string, string>>>(str);
            }
        }
        public static Dictionary<string, string> getJson(string str)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Deserialize<Dictionary<string, string>>(str);            
        }
        public static string getString(List<Dictionary<string, string>> _json)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(_json);
        }
        public static string getString(Dictionary<string, string> _json)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(_json);
        }
        public static string getString(Object _json)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(_json);
        }

        public Dictionary<string, string> find(string val,string Field)
        {
            return jsonList.Find(d => d[Field] == val);
        }

        /// <summary>
        /// 更新jsonList中记录
        /// _item 为Dictionary的Json对象
        /// 操作依据的Json字段名
        /// </summary>
        /// <param name="_item"></param>
        /// <param name="Field"></param>
        /// <returns></returns>
        public MyJsonStr updata(Dictionary<string, string> _item, string Field)
        {
            int index = jsonList.FindIndex(d => d[Field] == _item[Field]);
            if (index < 0){
                //不存name记录时增加新的
                jsonList.Add(_item);
            }
            else{
                //修改
                jsonList[index] = _item;
            }
            this.Jsonstr = getString(jsonList);
            return this;
        }
        /// <summary>
        /// 参数为List类型Dictionary元素
        /// Field为关键字段名。又来判断是否存在
        /// </summary>
        /// <param name="_items"></param>
        /// <param name="Field"></param>
        /// <returns></returns>
        public MyJsonStr updata(List<Dictionary<string, string>> _items, string Field)
        {
            foreach (var __item in _items)
            {
                updata(__item, Field);
            }
            return this;
        }
        public MyJsonStr updata(string jsonstr, string Field)
        {
            /*getJson(jsonstr);
            foreach (var __item in _items)
            {
                updata(__item, Field);
            }*/
            return this;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="val"></param>
        /// <param name="Field"></param>
        /// <returns></returns>
        public List<Dictionary<string, string>> del(string val,string Field)
        {
            jsonList.Remove(find(val,Field));
            return jsonList;
        }
        public List<Dictionary<string, string>> delById(string id)
        {
            jsonList.Remove(find(id, "id"));
            return jsonList;
        }
    }
    /// <summary>
    /// xml
    /// 准备把shop中item和其它用到jsonStr的字段 采用myJsonStr类，和大非商量*****
    /// jsonList的类型对象为特定json字段所服务
    /// </summary>
    public class MyJsonXML
    {
        public string Jsonstr;
        public XmlElement jsonList;

        public MyJsonXML(string str)
        {
            if (str == null)
            {
                this.Jsonstr = "";
                this.jsonList = null;
            }
            else
            {

                JavaScriptSerializer jss = new JavaScriptSerializer();
                this.jsonList = jss.Deserialize<XmlElement>(str);
            }
        }
        public static XmlElement getJson(string str)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Deserialize<XmlElement>(str);
        }
/*
        public Dictionary<string, string> find(string val, string Field)
        {
            return jsonList.@[Field] == val;
        }
        /// <summary>
        /// 更新jsonList中记录
        /// _item 为Dictionary的Json对象
        /// 操作依据的Json字段名
        /// </summary>
        /// <param name="_item"></param>
        /// <param name="Field"></param>
        /// <returns></returns>
        public MyJsonXML updata(string val, string Field)
        {
            int index = jsonList.FindIndex(d => d[Field] == _item[Field]);
            if (index < 0)
            {
                //不存name记录时增加新的
                jsonList.Add(_item);
            }
            else
            {
                //修改
                jsonList[index] = _item;
            }
            return this;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="val"></param>
        /// <param name="Field"></param>
        /// <returns></returns>
        public List<Dictionary<string, string>> del(string val, string Field)
        {
            jsonList.Remove(find(val, Field));
            return jsonList;
        }*/
    }

    /// <summary>
    /// 如名
    /// </summary>
    public class AjaxCallBackInfo
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="result">处理结果 ok,error</param>
        /// <param name="content">处理结果信息</param>
        /// <param name="code">代码</param>
        /// <returns></returns>
        public static string json(string result, string content, string code = "")
        {
            return "({code:'" + code + "',result:'" + result + "',content:'" + content + "'})";
        }

        public static string jsonOk(string content = "")
        {
            return json("ok", content);
        }

        public static string jsonError(string content = "")
        {
            return json("error", content);
        }
    }
}